<template>
    <PanelHead :route="route" />
    <div class="btns">
        <el-button :icon="Plus" type="primary" size="small" @click="open(null)">
            新增
        </el-button>

        <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled" icon-color="#626AEF"
            title="是否确定删除?" @confirm="handleDelete">
            <template #reference>
                <el-button :icon="DeleteFilled" type="danger" size="small">
                    删除
                </el-button>
            </template>
        </el-popconfirm>
    </div>
    <!-- 列表 -->
    <el-table :data="tableData.list" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column label="头像">
            <template #default="scope">
                <el-image :src="scope.row.avatar" style="width: 50px; height: 50px;" />
            </template>
        </el-table-column>
        <el-table-column label="性别">
            <template #default="scope">
                <span>{{ scope.row.sex == 1 ? '男' : '女' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="mobile" label="手机号"  width="140"/>
        <el-table-column prop="active" label="状态">
            <template #default="scope">
                <el-tag :type="scope.row.active == 1 ? 'success' : 'danger'">
                    {{ scope.row.active == 1 ? '正常' : '失效' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="创建时间" width="140">
            <template #default="scope">
                <div class="create-time">
                    <el-icon>
                        <Clock />
                    </el-icon>
                    <span style="margin-left: 10px;">{{ scope.row.create_time }}</span>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-info">
        <el-pagination v-model:current-page="paginationData.pageNum" :page-size="paginationData.pageSize"
            :background="false" layout="total, prev, pager, next" :total="tableData.total" size="small"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="outerVisible" :before-close="beforeClose" title="陪护师" width="500px">
        <el-form ref="formRef" label-width="100px" label-position="left" :model="form" :rules="rules">
            <el-form-item prop="id" v-show="false">
                <el-input v-model="form.id" />
            </el-form-item>
            <el-form-item label="昵称" prop="name">
                <el-input v-model="form.name" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="头像" prop="avatar">
                <el-button v-if="!form.avatar" type="primary" @click="openImg">
                    点击上传
                </el-button>
                <el-image v-else :src="form.avatar" style="width: 100px; height: 100px;" @click="openImg" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input-number v-model="form.age" :min="18" :max="50" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="是否生效" prop="active">
                <el-radio-group v-model="form.active">
                    <el-radio :value="0">生效</el-radio>
                    <el-radio :value="1">不生效</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button type="primary" @click="confirm(formRef)">确认</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 照片弹窗 -->
    <el-dialog v-model="outerVisibleImg" :before-close="beforeCloseImg" title="选择图片" width="680px">
        <div class="image-list">
            <div v-for="(item, index) in filerList" :key="item.name" class="img-box" @click="selectIndex = index">
                <div class="select" v-if="selectIndex === index">
                    <el-icon color="#fff">
                        <Check />
                    </el-icon>
                </div>
                <el-image :src="item.url" style="width: 148px; height: 148px;" />
            </div>
        </div>
        <template #footer>
            <div>
                <el-button @click="beforeCloseImg">取消</el-button>
                <el-button type="primary" @click="confirmImg">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue';
import type { FormInstance } from 'element-plus'
import { Plus, DeleteFilled, InfoFilled } from '@element-plus/icons-vue';
import dayjs from 'dayjs'
import { photoList, companionCreate, companionList, companionDelete } from '../../../api/index'; // 确保引入了相关API
import { useRoute } from 'vue-router'

// 获取pinia数据
const route = useRoute();
onMounted(() => {
    photoList().then(({ data }) => {
        filerList.value = data.data
    });
    getListData();
})
interface PaginationData {
    pageNum: string;
    pageSize: string;
}
interface tableDatalistType {
    active: number,
    age: number,
    avatar: string,
    create_time: number | string,
    id: number | string,
    mobile: string,
    name: string,
    permissions_id: number,
    sex: string
}
const paginationData = reactive<PaginationData>({
    pageNum: "1",
    pageSize: "10"
});
// 列表数据
const tableData = ref({
    list: [],
    total: 0
});
// 请求列表
const getListData = () => {
    companionList(paginationData).then(({ data }) => {
        // 处理响应数据
        const { list, total } = data.data;
        list.forEach((item: tableDatalistType) => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD')
        })
        tableData.value.list = list
        tableData.value.total = total
    });
}

// 头像数组
interface FileItem {
    name: string;
    url: string;
}
// 头像数据
const filerList = ref<FileItem[]>([]);
const outerVisible = ref<boolean>(false)
const outerVisibleImg = ref<boolean>(false)

// 分页控制
const handleSizeChange = (val: string) => {
    paginationData.pageSize = val;
}
const handleCurrentChange = (val: string) => {
    paginationData.pageNum = val;
}
// 打开弹窗 判断编辑还是新增
const open = (rowData: tableDatalistType | null) => {
    outerVisible.value = true;
    nextTick(() => {
        if (rowData) {
            Object.assign(form, rowData)
        }
    })
}
const openImg = () => {
    outerVisibleImg.value = true;
}
// 关闭弹窗的回调
const beforeClose = () => {
    outerVisible.value = false;
    formRef.value?.resetFields(); // 重置表单
}
const beforeCloseImg = () => {
    outerVisibleImg.value = false;
}
// 选中头像
const selectIndex = ref(0)
const confirmImg = () => {
    form.avatar = filerList.value[selectIndex.value].url
    outerVisibleImg.value = false;
}
// 表单数据
interface formType {
    active: number;
    age: number;
    avatar: string;
    id: number;
    mobile: string;
    name: string;
    sex: string;
}
const form: formType = reactive({
    id: 0,
    mobile: "",
    active: 1,
    age: 28,
    avatar: "",
    name: "",
    sex: ""
});
// 表单校验数据
const formRef = ref<FormInstance>()
//手机号校验规则
const validateUser = (rule: any, value: string, callback: (error?: Error) => void) => {
    // 检验手机号不为空
    if (value === '') {
        callback(new Error('请输入手机号'));
    } else {
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号'));
    }
}
// 表单校验 trigger:失去焦点的时候 
const rules = reactive({
    name: [{ required: true, trigger: 'blur', message: '请填写昵称' }],
    active: [{ required: true, message: '请选择头像' }],
    sex: [{ required: true, trigger: 'change', message: '请选择性别' }],
    mobile: [{ required: true, trigger: validateUser }],
})
const confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 手动触发表单校验
    await formEl.validate((valid, fields) => {
        if (valid) {
            companionCreate(form).then(({ data }) => {
                if (data.code === 10000) {
                    // 处理成功逻辑
                    ElMessage.success('操作成功');
                    beforeClose();
                    getListData();
                } else {
                    ElMessage.error(data.message || '操作失败');
                }
            })
        } else {
            // 处理表单校验失败
            console.log('error submit!', fields)
        }
    })
}

//列表选择
const selectable = (row: tableDatalistType) => {
    return true;
}
const multipleSelection = ref([])
const handleSelectionChange = (val: {
    map: (arg0: (
        item: { id: string; }) => { id: string; }) => never[];
}) => {
    multipleSelection.value = val.map((item: { id: string; }) => ({ id: item.id }));
}

// 删除
const handleDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的项');
        return;
    } else {
        companionDelete({ id: multipleSelection.value }).then(({ data }) => {
            if (data.code === 10000) {
                ElMessage.warning('删除成功')
                getListData();
            } else {
                ElMessage.error(data.message || '删除失败');
            }
        });
    }
}
</script>

<style scoped lang="less">
.btns {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}

.image-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .img-box {
        position: relative;

        .select {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 24px;
            height: 24px;
            background-color: #67c23a;
            z-index: 999;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }

    .el-image {
        margin-right: 10px;
        margin-bottom: 10px;
    }
}

.create-time {
    display: flex;
    align-items: center;
}
</style>